﻿// See https://aka.ms/new-console-template for more information
using System.Net;

using iTool.Center.Server;
using iTool.Cloud.Center.Model;
using iTool.Cloud.Database.KeyGeneratorProvider.Contract;
using iTool.ClusterComponent;
using iTool.Clustering.Center;
using iTool.Common;
using iTool.Common.Options;

using iToolService.Interfaces;

using Microsoft.Extensions.Configuration;

Console.WriteLine("Hello, World!");
//if (System.IO.Directory.Exists("./Storage"))
//{
//    System.IO.Directory.Delete("./Storage");
//}
try
{
    int port = 0;
    iPrint.Line("请输入端口号:");
    while (port == 0)
    {
        var input = Console.ReadLine();
        int.TryParse(input,out port);
        if (port < 10)
        {
            port += 20000;
        }
    }

    IConfigurationRoot configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile(path: "appsettings.json", optional: true, reloadOnChange: true)
                .Build();

    var builder = new iToolHostBuilder();

    var clusterOptions = new ClusteringStaticOptions(
        new ServiceEndPointOptions(configuration, true), 
        new ClusterIdentificationOptions(configuration, true));

    builder
        .UseiCenterClustering(
            new ClusterIdentificationOptions(),
            new EndpointsOptions
            {
                AdvertisedIP = IPAddress.Parse("127.0.0.1"),
                Port = port,
                GatewayPort = port + 111
            }, 
            clusterOptions)
        .UseiDateBaseProvide(new KeyGeneratorOptions());

    var handel = await builder.BuildAndStartAsync();

    var cluster = iBox.GetService<IClusterService>("IClusterService");

    // 内存流
    {
        iPrint.Line("\n内存流:");
        var subscribeStreamHandler = new TestSubscribeStreamHandler("zhangxiaosong", "user");
        await subscribeStreamHandler.StartAsync();

        var subscribeStreamHandler1 = new TestSubscribeStreamHandler("xxx1", "user");
        await subscribeStreamHandler1.StartAsync();

        var isub = cluster.GetService<ISubscribeService>("zhangxiaosong");
        await isub.Ping();
    }

    Console.ReadKey();
    await handel.StopAsync();
    Console.WriteLine("Stoped");

}
catch (Exception ex)
{
    Console.WriteLine(ex);
    Console.ReadKey();
}
